const url = require("url");
const express = require("express");
const router = express();
const bodyParser = require('body-parser');
router.use(bodyParser.urlencoded({ extended: true, limit: '500mb' }));
router.use(bodyParser.json({ limit: '500mb' }));
// router.use(bodyParser.urlencoded({extended: false, limit: '50mb'}));
const fs = require("fs")
const path = require('path');
// const iconv = require('iconv-lite');
const moment = require('moment');
const exe = require('../db/exe.js')
const $Config = require("../config.js"); //注意改成自己项目中mysql配置文件的路径
// const $identify1  = $Config.identify1;
// const $identify2  = $Config.identify2;
// const $identify3  = $Config.identify3;
const ButtonID =  $Config.ButtonID;

const $port = $Config.port;
const $url = "http://127.0.0.1:" + $port;
//使用db_nenghuan
const visual_db = require("../db/visual_db.js");
//检查进程是否运行
const execs = require('child_process').exec
const isRunning = (query, cb) => {
    let platform = process.platform
    let cmd = ''
    switch (platform) {
        case 'win32':
            cmd = `tasklist`
            break
        case 'darwin':
            cmd = `ps -ax | grep ${query}`
            break
        case 'linux':
            cmd = `ps -A`
            break
        default:
            break
    }
    execs(cmd, (err, stdout, stderr) => {
        cb(stdout.toLowerCase().indexOf(query.toLowerCase()) > -1)
    })
}
//查询应用运行状态
const appStatus = (appname,cb) =>{
    execs(`tasklist /FI "IMAGENAME eq ${appname}"`, (error, stdout, stderr) => {
        const list2 = [] 
        if (error) {
            console.error(`执行命令出错: ${error}`);
            cb(list2);
            return;
        }
        
        // 解析结果并输出PID
        const lines = stdout.replace('\r').split(/[\n]/);
        // console.log(lines)
       
        if (lines.length>2){
            for (let i = 3;i<lines.length;i++){
                if(lines[i]!=''){
                    list2.push(lines[i].split(/ +/)) ;
                }
            }
        }
        // console.log(list2)
        cb(list2)
    });
}
let getcmd = (swit)=>{
    var exec_path = ButtonID[swit].path
    // console.log(72,exec_path)
    if(exec_path!=''){
        const parts = exec_path.split(/[\\/]/);
        var appname = parts[parts.length-1].trim()
        return {cmd:exec_path,app:appname}
    }
    return null
}
// 路由访问
router.get('/visual', (req, res) => {
    const parentDir = path.resolve(__dirname, '..');
    const path2 =  path.join(parentDir,'public', 'html','visual.html')
    console.log(path2)
    // res.sendFile(path2);
    window.location.href = path2;
  });

// 定义 Express 路由和中间件
router.get('/', (req, res) => {
    res.send('Hello Express in Electron!');
  });


//视觉s识别系统 查询实时KNR号和结果------------------------------------
router.post("/getTableData", (req, res) => {
    res.setHeader('Access-Control-Allow-Origin', '*');
    var para = req.body.db
    // var para = "xiaozhi_eyes_210"
        // console.log(para,'参数')
    visual_db.getTableData("visual",para, res);
    // db.s7path("sql_s7", para, res);
})

//获取按钮信息------------------------------------
router.get("/getButtonInfo", (req, res) => {
    res.setHeader('Access-Control-Allow-Origin', '*');
    const keys = Object.keys($Config.ButtonID);
    res.send($Config.ButtonID)
})



    //QRK视觉管理系统 manage_qrk页面   读取图片文件  
router.post("/readImg", (req, res) => {
    let imgpath = req.body.path
        // console.log(imgpath)
    if(imgpath){
        fs.stat(imgpath, (err, data) => {
            if (err) {
                // console.log(err);
                res.send('300')
                return;
            }
            if (data.isFile()) {
                fs.readFile(imgpath, (err, data) => {
                    if (err) {
                        // console.log('读取错误', err);
                        res.send('300')
                        return;
                    }
                    // console.log(data, '读取文件成功');
                    const buffer = Buffer.from(data, 'binary');
                    const base64 = buffer.toString('base64');
                    res.send("data:image/jpeg;base64," +base64)
                        // res.send({
                        //     data: data,
                        // })
    
                    // console.log(data.toString()); //把Buffer转化成string类型
                })
            } else {
                res.send('300')
            }
            // console.log(data.isFile())
        })
    }else {
        res.send('300')
    }
    

}),



//控制exe程序
router.post('/Controlexe', (req, res) => {
    res.setHeader('Access-Control-Allow-Origin', '*')

    var para = req.body
    // console.log(para.switch)
    var pathname = getcmd(para.switch)
    
    if(pathname !=null){
        var exec_path = pathname.cmd
        var appname = pathname.app
        isRunning(appname, (status) => {
        // console.log(appname, status) // true|false、
        if (!status) {
            exe.Controlexe(exec_path,(status)=>{
                // if(status){
                //     res.end({
                //         code: '200',
                //         msg: "程序启动成功！",
                //     })
                // }else{
                //     res.end({
                //         code: '400',
                //         msg: "程序启动失败！",
                //     })
                // }
              
            })
            return
        }else{
            // console.log("程序已运行，关闭后才可再启动！")
            res.json({
                code: '400',
                msg: "程序已运行，关闭后才可再启动！",
            })
            // console.log("程序已运行，请关闭后再启动！")
        }
        })
        
        }
        
}),
//查看mul.exe运行状态
router.post('/AppStatue', (req, res) => {
    res.setHeader('Access-Control-Allow-Origin', '*')
    var para = req.body
     // 执行 tasklist 命令
    var pathname = getcmd(para.switch)
    if(pathname !=null){
        var exec_path = pathname.cmd
        var appname = pathname.app
        // console.log(208,appname)
        appStatus(appname,(infor)=> {
            // console.log('mul.exe', status) // true|false
            res.json({
                Code: 200,
                msg: infor,
            })
        })
    }
}),


router.get("/queryAll_data", (req, res, next) => {
    visual_db.dbQueryAll("user", "", res, next);
});

router.post("/closeEXE", (req, res, next) => {
    res.setHeader('Access-Control-Allow-Origin', '*')
    var para = req.body
    // console.log(226,para)
    // var cmd = "taskkill /F /T /PID " + para.PID
    var cmd =  'taskkill /f /t /im ' +  para.name
    // console.log(cmd)
    execs(cmd, (err, stdout, stderr) => {
        if(err){
            // console.log("1111命令错误")
            res.json({
                Code: 300,
                msg: '错误',
            })
            return
        }else{
            // console.log("2222命令执行")
            res.json({
                Code: 200,
                msg: stdout,
            })
            
        }
    })
});

    module.exports = router